<?php

namespace App\Http\Controllers\Admin;

use App\Model\CaptchaRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends \App\Http\Controllers\AuthController
{
    protected $middlewareName = 'adminJWT';

    protected function loginFields()
    {
        return ['account','password'];
    }

    protected function beforeLogin()
    {
        return ['success'=>true];

        $input = request(['captcha_key','captcha']);

        if ($input['captcha_key'] && $input['captcha']){

            $m = CaptchaRecord::findByKey($input['captcha_key']);
            if ($m && $m->code == strtolower($input['captcha'])){
                if ( strtotime($m->created_at) + 3*60 > time()  && $m->state == 1) {
                    $m->state = 0;
                    $m->save();
                    return ['success'=>true];
                }else{
                    return ['success'=>false,'error'=>'验证码已失效，请刷新验证码！'];
                }
            }

            return ['success'=>false,'error'=>'验证码错误'];

        }else{
            return ['success'=>false,'error'=>'验证码必填'];
        }
    }

    public function changePassword(Request $request)
    {
        $rules = [
            'old_password'=>'required',
            'password'=>'required|between:6,50|confirmed',
        ];

        $messages = [
            'required' => '密码不能为空',
            'between' => '密码必须是6~50位之间',
            'confirmed' => '新密码和确认密码不匹配'
        ];

        $user = auth()->user();

        $validator = Validator::make($request->all(),$rules,$messages);

        $old_password = $request->input('old_password');

        $validator->after(function($validator) use ($old_password, $user) {
            if (!\Hash::check($old_password, $user->password)) { //原始密码和数据库里的密码进行比对
                $validator->errors()->add('old_password', '原密码错误'); //错误的话显示原始密码错误
            }
        });

        if($validator->fails()){
            return $this->failed($validator->errors()->first());
        }

        $user->password = bcrypt($request->input('password'));
        $user->save();
        auth()->logout();

        return $this->message('修改成功');

    }
}
